import sqlite3
from datetime import datetime, date
import getpass


class SupermarketManagementSystem:
    def __init__(self, db_name='supermarket.db'):
        self.db_name = db_name
        self.init_database()

    def init_database(self):
        """初始化数据库表结构"""
        conn = sqlite3.connect(self.db_name)
        cursor = conn.cursor()

        # 创建商品表
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS products (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT NOT NULL,
                barcode TEXT UNIQUE,
                category TEXT,
                purchase_price REAL NOT NULL,
                sale_price REAL NOT NULL,
                stock_quantity INTEGER DEFAULT 0,
                min_stock INTEGER DEFAULT 10,
                supplier TEXT,
                created_date TEXT,
                updated_date TEXT
            )
        ''')

        # 创建会员表
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS members (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT NOT NULL,
                phone TEXT UNIQUE,
                points INTEGER DEFAULT 0,
                level TEXT DEFAULT '普通',
                registration_date TEXT,
                total_consumption REAL DEFAULT 0
            )
        ''')

        # 创建销售记录表
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS sales (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                sale_number TEXT UNIQUE,
                member_id INTEGER,
                total_amount REAL,
                payment_method TEXT,
                sale_date TEXT,
                FOREIGN KEY (member_id) REFERENCES members (id)
            )
        ''')

        # 创建销售明细表
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS sale_details (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                sale_id INTEGER,
                product_id INTEGER,
                quantity INTEGER,
                unit_price REAL,
                subtotal REAL,
                FOREIGN KEY (sale_id) REFERENCES sales (id),
                FOREIGN KEY (product_id) REFERENCES products (id)
            )
        ''')

        # 创建库存操作记录表
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS inventory_operations (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                product_id INTEGER,
                operation_type TEXT,
                quantity INTEGER,
                previous_stock INTEGER,
                current_stock INTEGER,
                operation_date TEXT,
                operator TEXT,
                note TEXT,
                FOREIGN KEY (product_id) REFERENCES products (id)
            )
        ''')

        conn.commit()
        conn.close()

    def get_connection(self):
        """获取数据库连接"""
        return sqlite3.connect(self.db_name)


class ProductManager:
    def __init__(self, system):
        self.system = system

    def add_product(self):
        """添加商品"""
        print("\n=== 添加商品 ===")
        name = input("商品名称: ")
        barcode = input("条形码: ")
        category = input("商品类别: ")

        try:
            purchase_price = float(input("进货价: "))
            sale_price = float(input("售价: "))
            stock_quantity = int(input("库存数量: "))
            min_stock = int(input("最低库存预警: "))
        except ValueError:
            print("输入格式错误！")
            return

        supplier = input("供应商: ")
        current_time = datetime.now().isoformat()

        conn = self.system.get_connection()
        cursor = conn.cursor()

        try:
            cursor.execute('''
                INSERT INTO products 
                (name, barcode, category, purchase_price, sale_price, stock_quantity, min_stock, supplier, created_date, updated_date)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ''', (
            name, barcode, category, purchase_price, sale_price, stock_quantity, min_stock, supplier, current_time,
            current_time))

            conn.commit()
            print(f"商品 '{name}' 添加成功！")
        except sqlite3.IntegrityError:
            print("条形码已存在！")
        finally:
            conn.close()

    def update_product(self):
        """更新商品信息"""
        print("\n=== 更新商品信息 ===")
        product_id = input("输入商品ID: ")

        conn = self.system.get_connection()
        cursor = conn.cursor()

        cursor.execute("SELECT * FROM products WHERE id = ?", (product_id,))
        product = cursor.fetchone()

        if not product:
            print("商品不存在！")
            conn.close()
            return

        print(f"\n当前信息: {product[1]} - 售价: {product[5]} - 库存: {product[6]}")

        try:
            sale_price = float(input("新售价 (留空保持不变): ") or product[5])
            stock_quantity = int(input("新库存数量 (留空保持不变): ") or product[6])
            min_stock = int(input("新最低库存预警 (留空保持不变): ") or product[7])
        except ValueError:
            print("输入格式错误！")
            conn.close()
            return

        current_time = datetime.now().isoformat()

        cursor.execute('''
            UPDATE products 
            SET sale_price = ?, stock_quantity = ?, min_stock = ?, updated_date = ?
            WHERE id = ?
        ''', (sale_price, stock_quantity, min_stock, current_time, product_id))

        conn.commit()
        conn.close()
        print("商品信息更新成功！")

    def search_products(self):
        """搜索商品"""
        print("\n=== 搜索商品 ===")
        keyword = input("输入商品名称或条形码 (留空显示所有): ")

        conn = self.system.get_connection()
        cursor = conn.cursor()

        if keyword:
            cursor.execute('''
                SELECT * FROM products 
                WHERE name LIKE ? OR barcode LIKE ?
            ''', (f'%{keyword}%', f'%{keyword}%'))
        else:
            cursor.execute("SELECT * FROM products ORDER BY id")

        products = cursor.fetchall()
        conn.close()

        if not products:
            print("没有找到商品！")
            return

        print(f"\n{'ID':<5} {'名称':<15} {'条形码':<15} {'类别':<10} {'售价':<8} {'库存':<6}")
        print("-" * 70)
        for product in products:
            stock_warning = "⚠" if product[6] <= product[7] else ""
            print(
                f"{product[0]:<5} {product[1]:<15} {product[2]:<15} {product[3]:<10} {product[5]:<8} {product[6]:<6}{stock_warning}")


class SalesManager:
    def __init__(self, system):
        self.system = system

    def make_sale(self):
        """进行销售"""
        print("\n=== 收银销售 ===")
        sale_items = []
        total_amount = 0

        while True:
            product_id = input("输入商品ID (输入 'done' 结束): ")
            if product_id.lower() == 'done':
                break

            conn = self.system.get_connection()
            cursor = conn.cursor()
            cursor.execute("SELECT * FROM products WHERE id = ?", (product_id,))
            product = cursor.fetchone()
            conn.close()

            if not product:
                print("商品不存在！")
                continue

            if product[6] <= 0:
                print("商品库存不足！")
                continue

            try:
                quantity = int(input(f"输入数量 (库存: {product[6]}): "))
            except ValueError:
                print("数量必须是数字！")
                continue

            if quantity > product[6]:
                print("库存不足！")
                continue

            subtotal = product[5] * quantity
            sale_items.append({
                'product_id': product_id,
                'product_name': product[1],
                'quantity': quantity,
                'unit_price': product[5],
                'subtotal': subtotal
            })
            total_amount += subtotal

            print(f"添加: {product[1]} x {quantity} = ¥{subtotal:.2f}")

        if not sale_items:
            print("没有添加商品！")
            return

        print(f"\n总计: ¥{total_amount:.2f}")

        # 会员积分
        member_id = None
        phone = input("会员手机号 (留空跳过): ")
        if phone:
            conn = self.system.get_connection()
            cursor = conn.cursor()
            cursor.execute("SELECT * FROM members WHERE phone = ?", (phone,))
            member = cursor.fetchone()
            if member:
                member_id = member[0]
                points_earned = int(total_amount)
                cursor.execute('''
                    UPDATE members 
                    SET points = points + ?, total_consumption = total_consumption + ?
                    WHERE id = ?
                ''', (points_earned, total_amount, member_id))
                print(f"会员 {member[1]} 获得 {points_earned} 积分")
            conn.close()

        # 记录销售
        conn = self.system.get_connection()
        cursor = conn.cursor()

        sale_number = f"SN{datetime.now().strftime('%Y%m%d%H%M%S')}"
        sale_date = datetime.now().isoformat()
        payment_method = input("支付方式 (现金/微信/支付宝): ") or "现金"

        cursor.execute('''
            INSERT INTO sales (sale_number, member_id, total_amount, payment_method, sale_date)
            VALUES (?, ?, ?, ?, ?)
        ''', (sale_number, member_id, total_amount, payment_method, sale_date))

        sale_id = cursor.lastrowid

        # 记录销售明细并更新库存
        for item in sale_items:
            cursor.execute('''
                INSERT INTO sale_details (sale_id, product_id, quantity, unit_price, subtotal)
                VALUES (?, ?, ?, ?, ?)
            ''', (sale_id, item['product_id'], item['quantity'], item['unit_price'], item['subtotal']))

            # 更新库存
            cursor.execute('''
                UPDATE products 
                SET stock_quantity = stock_quantity - ?, updated_date = ?
                WHERE id = ?
            ''', (item['quantity'], sale_date, item['product_id']))

        conn.commit()
        conn.close()

        # 打印小票
        self.print_receipt(sale_items, total_amount, sale_number, payment_method)

    def print_receipt(self, items, total_amount, sale_number, payment_method):
        """打印销售小票"""
        print("\n" + "=" * 40)
        print("           超市销售小票")
        print("=" * 40)
        print(f"流水号: {sale_number}")
        print(f"时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        print("-" * 40)

        for item in items:
            print(f"{item['product_name']:<15} x{item['quantity']:<3} ¥{item['subtotal']:>7.2f}")

        print("-" * 40)
        print(f"总计: ¥{total_amount:>26.2f}")
        print(f"支付方式: {payment_method:>24}")
        print("=" * 40)
        print("        谢谢惠顾，欢迎下次光临！")
        print("=" * 40)


class MemberManager:
    def __init__(self, system):
        self.system = system

    def register_member(self):
        """注册会员"""
        print("\n=== 注册会员 ===")
        name = input("姓名: ")
        phone = input("手机号: ")

        if not phone:
            print("手机号不能为空！")
            return

        registration_date = datetime.now().isoformat()

        conn = self.system.get_connection()
        cursor = conn.cursor()

        try:
            cursor.execute('''
                INSERT INTO members (name, phone, registration_date)
                VALUES (?, ?, ?)
            ''', (name, phone, registration_date))

            conn.commit()
            print(f"会员 {name} 注册成功！")
        except sqlite3.IntegrityError:
            print("该手机号已注册！")
        finally:
            conn.close()

    def view_members(self):
        """查看会员列表"""
        conn = self.system.get_connection()
        cursor = conn.cursor()

        cursor.execute("SELECT * FROM members ORDER BY id")
        members = cursor.fetchall()
        conn.close()

        if not members:
            print("没有会员记录！")
            return

        print(f"\n{'ID':<5} {'姓名':<10} {'手机号':<15} {'积分':<8} {'等级':<8} {'总消费':<10}")
        print("-" * 65)
        for member in members:
            print(f"{member[0]:<5} {member[1]:<10} {member[2]:<15} {member[3]:<8} {member[4]:<8} ¥{member[6]:<9.2f}")


class InventoryManager:
    def __init__(self, system):
        self.system = system

    def check_low_stock(self):
        """检查低库存商品"""
        conn = self.system.get_connection()
        cursor = conn.cursor()

        cursor.execute('''
            SELECT * FROM products 
            WHERE stock_quantity <= min_stock 
            ORDER BY stock_quantity ASC
        ''')

        low_stock_products = cursor.fetchall()
        conn.close()

        if not low_stock_products:
            print("没有低库存商品！")
            return

        print("\n=== 低库存预警 ===")
        print(f"{'ID':<5} {'名称':<15} {'当前库存':<8} {'最低库存':<8}")
        print("-" * 45)
        for product in low_stock_products:
            print(f"{product[0]:<5} {product[1]:<15} {product[6]:<8} {product[7]:<8}")


class ReportManager:
    def __init__(self, system):
        self.system = system

    def sales_report(self):
        """销售报表"""
        print("\n=== 销售报表 ===")
        date_str = input("输入日期 (YYYY-MM-DD，留空显示今天): ") or date.today().isoformat()

        conn = self.system.get_connection()
        cursor = conn.cursor()

        cursor.execute('''
            SELECT s.sale_number, s.total_amount, s.payment_method, s.sale_date,
                   m.name as member_name
            FROM sales s
            LEFT JOIN members m ON s.member_id = m.id
            WHERE date(s.sale_date) = ?
            ORDER BY s.sale_date DESC
        ''', (date_str,))

        sales = cursor.fetchall()

        total_sales = sum(sale[1] for sale in sales)

        print(f"\n{date_str} 销售记录:")
        print(f"{'流水号':<15} {'金额':<10} {'支付方式':<8} {'会员':<10} {'时间':<8}")
        print("-" * 60)
        for sale in sales:
            time_str = sale[3][11:16]  # 只显示时间部分
            print(f"{sale[0]:<15} ¥{sale[1]:<8.2f} {sale[2]:<8} {sale[4] or '非会员':<10} {time_str:<8}")

        print(f"\n当日总销售额: ¥{total_sales:.2f}")
        print(f"订单数量: {len(sales)}")

        conn.close()


def main():
    """主程序"""
    system = SupermarketManagementSystem()
    product_manager = ProductManager(system)
    sales_manager = SalesManager(system)
    member_manager = MemberManager(system)
    inventory_manager = InventoryManager(system)
    report_manager = ReportManager(system)

    while True:
        print("\n" + "=" * 50)
        print("           超市信息管理系统")
        print("=" * 50)
        print("1. 商品管理")
        print("2. 收银销售")
        print("3. 会员管理")
        print("4. 库存管理")
        print("5. 报表统计")
        print("6. 退出系统")
        print("-" * 50)

        choice = input("请选择操作 (1-6): ")

        if choice == '1':
            # 商品管理子菜单
            print("\n--- 商品管理 ---")
            print("1. 添加商品")
            print("2. 更新商品")
            print("3. 搜索商品")
            sub_choice = input("请选择: ")

            if sub_choice == '1':
                product_manager.add_product()
            elif sub_choice == '2':
                product_manager.update_product()
            elif sub_choice == '3':
                product_manager.search_products()

        elif choice == '2':
            sales_manager.make_sale()

        elif choice == '3':
            # 会员管理子菜单
            print("\n--- 会员管理 ---")
            print("1. 注册会员")
            print("2. 查看会员")
            sub_choice = input("请选择: ")

            if sub_choice == '1':
                member_manager.register_member()
            elif sub_choice == '2':
                member_manager.view_members()

        elif choice == '4':
            inventory_manager.check_low_stock()

        elif choice == '5':
            report_manager.sales_report()

        elif choice == '6':
            print("感谢使用超市管理系统！")
            break

        else:
            print("无效选择，请重新输入！")

        input("\n按回车键继续...")


if __name__ == "__main__":
    main()